import fs from "fs";
import path from "path";

function getTotalFolder(basePath) {
    let resAliasObj = {};

    resAliasObj["@"] = path.resolve(__dirname, basePath);

    const dirArr = fs.readdirSync(path.resolve(__dirname, basePath));
    dirArr.forEach((fileOrDirName) => {
        let statInfo = fs.statSync(
            path.resolve(__dirname, basePath, fileOrDirName)
        );
        if (statInfo.isDirectory()) {
            resAliasObj[`@${fileOrDirName}`] = path.resolve(
                __dirname,
                basePath,
                fileOrDirName
            );
        }
    });
    return resAliasObj;
}

export default () => {
    return {
        //config钩子，在解析 Vite 配置前调用。将最终返回的对象与vite.config.js合并，作为最终的vite配置
        config(config, env) {
            //注意，插件是在Vite中处理（Node环境），所以这里的输出在Node的控制台
            console.log("config-->", config); //vite.config.js中的配置对象
            console.log("env-->", env); // { mode: 'development', command: 'serve', ssrBuild: false }

            let aliasObj = getTotalFolder("../src");
            console.log(aliasObj);
            return {
                resolve: {
                    alias: aliasObj,
                },
            };
        },
    };
};
